<template>
  <div class="resource-property-manager-v2">
    <div class="manager-header">
      <h2>资源属性管理 (useVbenForm版本)</h2>
      <div class="header-actions">
        <Button type="primary" @click="saveSchema" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存结构
        </Button>
        <Button @click="previewForm">
          <IconifyIcon icon="ant-design:eye-outlined" />
          预览表单
        </Button>
      </div>
    </div>

    <Tabs v-model:active-key="activeTab" class="manager-tabs">
      <TabPane key="schema" tab="属性结构">
        <div class="schema-editor">
          <div class="toolbar">
            <Button type="primary" @click="addField">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加字段
            </Button>
            <Button @click="exportSchema">
              <IconifyIcon icon="ant-design:export-outlined" />
              导出结构
            </Button>
          </div>

          <div class="fields-list">
            <div
              v-for="(field, index) in schemaFields"
              :key="field.id"
              class="field-item"
              :class="{ 'field-item--selected': selectedFieldId === field.id }"
              @click="selectField(field.id)"
            >
              <div class="field-info">
                <div class="field-header">
                  <IconifyIcon :icon="getFieldTypeIcon(field.type)" />
                  <span class="field-name">{{
                    field.label || field.name
                  }}</span>
                  <Tag :color="getFieldTypeColor(field.type)">
                    {{ getFieldTypeName(field.type) }}
                  </Tag>
                  <Tag v-if="field.required" color="red">必填</Tag>
                </div>
                <div class="field-details">
                  <span>字段名: {{ field.name }}</span>
                  <span v-if="field.uiConfig?.placeholder">
                    占位符: {{ field.uiConfig.placeholder }}
                  </span>
                </div>
              </div>
              <div class="field-actions">
                <Button type="link" size="small" @click.stop="editField(index)">
                  <IconifyIcon icon="ant-design:edit-outlined" />
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click.stop="removeField(index)"
                >
                  <IconifyIcon icon="ant-design:delete-outlined" />
                  删除
                </Button>
              </div>
            </div>
          </div>
        </div>
      </TabPane>

      <TabPane key="data" tab="属性数据">
        <div class="data-editor">
          <div class="toolbar">
            <Button type="primary" @click="saveData" :loading="savingData">
              <IconifyIcon icon="ant-design:save-outlined" />
              保存数据
            </Button>
            <Button @click="loadData">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重新加载
            </Button>
          </div>

          <div class="dynamic-form-container">
            <Form />
          </div>
        </div>
      </TabPane>
    </Tabs>

    <!-- 字段编辑器模态框 -->
    <Modal
      v-model:visible="fieldEditorVisible"
      title="字段配置"
      width="600px"
      :footer="null"
      :destroyOnClose="true"
    >
      <FieldEditorV2
        v-if="editingField"
        :field="editingField"
        @update="updateEditingField"
        @cancel="fieldEditorVisible = false"
      />
    </Modal>

    <!-- 表单预览模态框 -->
    <Modal
      v-model:visible="previewVisible"
      title="VbenForm 表单预览"
      width="900px"
      :footer="null"
      :destroyOnClose="true"
    >
      <PropertyFormPreview
        v-if="previewVisible"
        :schema="convertToVbenSchema()"
        :data="{}"
        @form-change="handlePreviewFormChange"
      />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Tabs, TabPane, Button, Modal, Tag, message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { useVbenForm } from '#/adapter/form';
import type { VbenFormSchema } from '#/adapter/form';
import FieldEditorV2 from './FieldEditorV2.vue';
import PropertyFormPreview from './PropertyFormPreview.vue';
import {
  getPropertySchema,
  savePropertySchema,
  getPropertyData,
  savePropertyData,
} from '#/api/resource-center';

// 工具函数
const generateId = () => {
  return 'id_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// Props
const props = defineProps<{
  resource: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
}>();

// 响应式数据
const activeTab = ref('schema');
const saving = ref(false);
const savingData = ref(false);
const selectedFieldId = ref('');

// 字段编辑器相关
const fieldEditorVisible = ref(false);
const editingField = ref<any>(null);

// 预览相关
const previewVisible = ref(false);

// 数据结构
const schemaFields = ref<any[]>([]);

// 动态表单相关
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: computed(() => generateFormSchema()),
  showDefaultActions: false,
});

// 生成表单Schema
const generateFormSchema = (): VbenFormSchema[] => {
  try {
    return schemaFields.value
      .map((field) => {
        if (!field || !field.name) {
          console.warn('字段数据不完整:', field);
          return null;
        }

        const schema: VbenFormSchema = {
          fieldName: field.name,
          label: field.label || field.name,
          component: getComponentByType(field.type),
          componentProps: {
            placeholder: field.uiConfig?.placeholder,
            ...field.uiConfig,
          },
          rules: generateFieldRules(field),
        };

        // 处理特殊组件类型
        if (field.type === 'SELECT' && field.options) {
          schema.componentProps.options = field.options;
        }

        return schema;
      })
      .filter(Boolean) as VbenFormSchema[];
  } catch (error) {
    console.error('生成表单Schema时出错:', error);
    return [];
  }
};

// 根据字段类型获取组件
const getComponentByType = (type: string): string => {
  const typeMap: Record<string, string> = {
    STRING: 'Input',
    TEXT: 'Input', // 后端返回TEXT类型，映射到Input组件;
    NUMBER: 'InputNumber',
    BOOLEAN: 'Switch',
    DATE: 'DatePicker',
    SELECT: 'Select',
    TEXTAREA: 'Textarea',
    UPLOAD: 'Upload',
  };
  return typeMap[type] || 'Input';
};

// 生成字段验证规则
const generateFieldRules = (field: any) => {
  // VbenForm使用Zod验证，返回字符串规则名
  if (field.required) {
    return 'required';
  }

  return undefined;
};

// 字段类型相关方法
const getFieldTypeIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    STRING: 'ant-design:font-size-outlined',
    TEXT: 'ant-design:font-size-outlined', // 后端返回TEXT类型;
    NUMBER: 'ant-design:number-outlined',
    BOOLEAN: 'ant-design:check-square-outlined',
    DATE: 'ant-design:calendar-outlined',
    SELECT: 'ant-design:down-outlined',
    TEXTAREA: 'ant-design:file-text-outlined',
    UPLOAD: 'ant-design:upload-outlined',
  };
  return iconMap[type] || 'ant-design:question-outlined';
};

const getFieldTypeColor = (type: string): string => {
  const colorMap: Record<string, string> = {
    STRING: 'blue',
    TEXT: 'blue', // 后端返回TEXT类型;
    NUMBER: 'green',
    BOOLEAN: 'orange',
    DATE: 'purple',
    SELECT: 'cyan',
    TEXTAREA: 'geekblue',
    UPLOAD: 'magenta',
  };
  return colorMap[type] || 'default';
};

const getFieldTypeName = (type: string): string => {
  const nameMap: Record<string, string> = {
    STRING: '文本',
    TEXT: '文本', // 后端返回TEXT类型;
    NUMBER: '数字',
    BOOLEAN: '布尔',
    DATE: '日期',
    SELECT: '选择',
    TEXTAREA: '多行文本',
    UPLOAD: '文件上传',
  };
  return nameMap[type] || '未知';
};

// 字段管理方法
const addField = () => {
  const newField = {
    id: generateId(),
    name: '',
    label: '',
    type: 'STRING',
    required: false,
    defaultValue: '',
    validation: {},
    uiConfig: {},
  };
  schemaFields.value.push(newField);
  selectField(newField.id);
  editField(schemaFields.value.length - 1);
};

const selectField = (fieldId: string) => {
  selectedFieldId.value = fieldId;
};

const editField = (index: number) => {
  editingField.value = { ...schemaFields.value[index] };
  fieldEditorVisible.value = true;
};

const updateEditingField = (field: any) => {
  const index = schemaFields.value.findIndex((f) => f.id === field.id);
  if (index !== -1) {
    schemaFields.value[index] = { ...field };
  }
  fieldEditorVisible.value = false;
  editingField.value = null;
};

const removeField = (index: number) => {
  schemaFields.value.splice(index, 1);
  if (selectedFieldId.value === schemaFields.value[index]?.id) {
    selectedFieldId.value = '';
  }
};

// 保存和加载方法
const saveSchema = async () => {
  saving.value = true;
  try {
    // 修复数据结构：按照后端期望的格式
    const schema = {
      resourceId: props.resource.id,
      schema: {
        fields: schemaFields.value,
      },
    };

    const result = await savePropertySchema(schema);

    if (result.code === 200) {
      message.success('属性结构保存成功');
      emit('update', schema);
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    message.error('保存失败: ' + error.message);
  } finally {
    saving.value = false;
  }
};

const saveData = async () => {
  savingData.value = true;
  try {
    const formData = await formApi.getValues();
    const data = {
      resourceId: props.resource.id,
      data: formData,
    };

    const result = await savePropertyData(data);

    if (result.code === 200) {
      message.success('属性数据保存成功');
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    message.error('保存失败: ' + error.message);
  } finally {
    savingData.value = false;
  }
};

const loadData = async () => {
  try {
    const result = await getPropertyData({ resourceId: props.resource.id });
    if (result.code === 200 && result.data) {
      await formApi.setValues(result.data);
      message.success('数据加载成功');
    }
  } catch (error) {
    message.error('数据加载失败: ' + error.message);
  }
};

// 导出方法
const exportSchema = () => {
  const schema = {
    fields: schemaFields.value,
  };

  const blob = new Blob([JSON.stringify(schema, null, 2)], {
    type: 'application/json',
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `resource-schema-${props.resource.id}.json`;
  a.click();
  URL.revokeObjectURL(url);
};

// 预览方法
const previewForm = () => {
  previewVisible.value = true;
};

// 转换为VbenSchema格式用于预览
const convertToVbenSchema = () => {
  return schemaFields.value.map((field: any) => ({
    fieldName: field.name,
    label: field.label,
    component: getComponentByType(field.type),
    componentProps: {
      placeholder: field.uiConfig?.placeholder || `请输入${field.label}`,
      ...field.uiConfig?.componentProps,
    },
    rules: field.required ? 'required' : undefined,
    defaultValue: field.defaultValue,
  }));
};

// 预览表单数据变化处理
const handlePreviewFormChange = (values: Record<string, any>) => {
  console.log('预览表单数据变化:', values);
};

// 初始化
onMounted(async () => {
  try {
    // 首先尝试从资源属性中解析数据
    if (props.resource?.properties) {
      const properties = JSON.parse(props.resource.properties);

      // 处理新的VbenFormSchema格式
      if (properties.schema && Array.isArray(properties.schema)) {
        // 新格式：VbenFormSchema
        schemaFields.value = properties.schema.map((field: any) => ({
          id: field.fieldName || generateId(),
          name: field.fieldName || '',
          label: field.label || '',
          type: getFieldTypeFromComponent(field.component),
          required: field.rules === 'required',
          defaultValue: field.defaultValue || '',
          validation: {},
          uiConfig: {
            component: field.component,
            componentProps: field.componentProps || {},
          },
        }));
        console.log(
          '从资源属性解析Schema成功，字段数量:',
          schemaFields.value.length,
        );
        return;
      }
    }

    // 如果资源属性中没有数据，尝试API调用
    const result = await getPropertySchema({ resourceId: props.resource.id });

    if (result.code === 200 && result.data) {
      // 修复数据结构访问路径：data.schema.fields
      const fields = result.data.schema?.fields || [];

      // 为每个字段添加ID，如果字段没有ID的话
      schemaFields.value = fields.map((field: any) => ({
        ...field,
        id: field.id || generateId(),
      }));

      console.log('属性Schema加载成功，字段数量:', schemaFields.value.length);
    } else {
      console.warn('响应状态异常:', result);
    }
  } catch (error) {
    console.error('加载属性Schema失败:', error);
  }
});

// 根据组件类型获取字段类型
const getFieldTypeFromComponent = (component: string) => {
  const typeMap: Record<string, string> = {
    Input: 'STRING',
    InputNumber: 'NUMBER',
    Select: 'SELECT',
    Switch: 'BOOLEAN',
    DatePicker: 'DATE',
    Textarea: 'TEXTAREA',
    Upload: 'UPLOAD',
  };
  return typeMap[component] || 'STRING';
};

// 监听Schema变化，更新表单
watch(
  schemaFields,
  () => {
    // Schema变化时，表单会自动重新生成
  },
  { deep: true },
);
</script>

<style lang="less" scoped>
.resource-property-manager-v2 {
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .manager-tabs {
    :deep(.ant-tabs-content) {
      padding: 16px 0;
    }
  }

  .toolbar {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }

  .fields-list {
    .field-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      margin-bottom: 8px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
      }

      &--selected {
        border-color: #1890ff;
        background-color: #f6ffed;
      }

      .field-info {
        flex: 1;

        .field-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;

          .field-name {
            font-weight: 500;
            color: #262626;
          }
        }

        .field-details {
          display: flex;
          gap: 16px;
          font-size: 12px;
          color: #8c8c8c;
        }
      }

      .field-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .dynamic-form-container {
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 20px;
    background-color: #fafafa;
  }

  .form-preview {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
  }
}
</style>
